<template>
  <div class="flipper-container" :style="containerStyle">
    <div class="flipper-wrapper">
      <div class="flipper-content" :style="contentStyle">
        <span v-if="prefixText" class="flipper-prefix" :style="glowStyle">{{ prefixText }}</span>
        <!-- 将数值拆分为单个数字并添加边框控制 -->
        <template v-if="isDigitBorderEnabled">
          <span 
            v-for="(digit, index) in digitArray" 
            :key="index"
            class="flipper-digit"
            :style="digitStyle"
          >{{ digit }}</span>
        </template>
        <!-- 默认显示方式 -->
        <span v-else class="flipper-value" :style="glowStyle">{{ displayValue }}</span>
        <span v-if="suffixText" class="flipper-suffix" :style="glowStyle">{{ suffixText }}</span>
      </div>
    </div>
  </div>
</template>

<script>
import { targetWidgetLinkageLogic } from "@/views/bigscreenDesigner/designer/linkageLogic";

export default {
  name: "WidgetFlipper",
  components: {},
  props: {
    value: Object,
    ispreview: Boolean
  },
  data() {
    return {
      options: {},
      optionsData: {},
      optionsSetup: {},
      flagInter: null,
      currentValue: 0,
      previousValue: 0,
      animationStartTime: 0,
      animationDuration: 1000,
      animationRunning: false,
    };
  },
  computed: {
    containerStyle() {
      return {
        position: this.ispreview ? "absolute" : "static",
        width: this.optionsStyle.width + "px",
        height: this.optionsStyle.height + "px",
        left: this.optionsStyle.left + "px",
        top: this.optionsStyle.top + "px",
        background: this.optionsSetup.background,
        // 外边框属性实现
        border: this.hasOuterBorder ? 
          `${this.optionsSetup.borderWidth}px ${this.optionsSetup.borderStyle || 'solid'} ${this.optionsSetup.borderColor || '#000'}` : 
          'none',
        borderRadius: this.optionsSetup.borderRadius ? this.optionsSetup.borderRadius + "px" : "0px",
        overflow: "hidden",
      };
    },
    // 判断是否启用外边框
    hasOuterBorder() {
      return this.optionsSetup.borderWidth && this.optionsSetup.borderWidth > 0;
    },
    // 判断是否启用数字边框
    isDigitBorderEnabled() {
      return this.optionsSetup.digitBorderEnabled === true && 
             this.optionsSetup.digitBorderWidth !== undefined && 
             this.optionsSetup.digitBorderWidth > 0;
    },
    contentStyle() {
      return {
        color: this.optionsSetup.color,
        "font-weight": this.optionsSetup.fontWeight,
        "font-size": this.optionsSetup.fontSize + "px",
        "font-family": this.optionsSetup.fontFamily || "Arial, sans-serif",
        "text-align": this.optionsSetup.textAlign,
        width: "100%",
        height: "100%",
        display: "flex",
        "align-items": "center",
        "justify-content": this.optionsSetup.textAlign === "left" ? "flex-start" : 
                          this.optionsSetup.textAlign === "right" ? "flex-end" : "center",
      };
    },
    // 单个数字的样式控制
    digitStyle() {
      const baseStyle = {
        color: this.optionsSetup.color,
        "font-weight": this.optionsSetup.fontWeight,
        "font-size": this.optionsSetup.fontSize + "px",
        "font-family": this.optionsSetup.fontFamily || "Arial, sans-serif",
        "text-align": "center",
        "display": "inline-block",
        "margin": "0 1px"
      };
      
      // 数字边框样式控制
      if (this.isDigitBorderEnabled) {
        baseStyle.border = `${this.optionsSetup.digitBorderWidth}px ${this.optionsSetup.digitBorderStyle || 'solid'} ${this.optionsSetup.digitBorderColor || '#000'}`;
        baseStyle.borderRadius = this.optionsSetup.digitBorderRadius ? this.optionsSetup.digitBorderRadius + "px" : "0px";
        
        // 添加digitPadding和digitMargin支持
        if (this.optionsSetup.digitPadding !== undefined) {
          baseStyle.padding = `${this.optionsSetup.digitPadding}px`;
        }
        
        if (this.optionsSetup.digitMargin !== undefined) {
          baseStyle.margin = `${this.optionsSetup.digitMargin}px`;
        }
      }
      
      // 发光效果
      if (this.optionsSetup.textGlow) {
        baseStyle["text-shadow"] = `0 0 ${this.optionsSetup.glowIntensity || 10}px ${this.optionsSetup.glowColor || this.optionsSetup.color}`;
      }
      
      return baseStyle;
    },
    // 将数值拆分为单个数字的数组
    digitArray() {
      return this.displayValue.toString().split('');
    },
    glowStyle() {
      if (this.optionsSetup.textGlow) {
        return {
          "text-shadow": `0 0 ${this.optionsSetup.glowIntensity || 10}px ${this.optionsSetup.glowColor || this.optionsSetup.color}`,
          "font-family": this.optionsSetup.fontFamily || "Arial, sans-serif"
        };
      }
      return {
        "font-family": this.optionsSetup.fontFamily || "Arial, sans-serif"
      };
    },
    optionsStyle() {
      return this.options.position || {};
    },
    prefixText() {
      return this.optionsSetup.prefix || "";
    },
    suffixText() {
      return this.optionsSetup.suffix || "";
    },
    displayValue() {
      // 格式化数值显示
      let value = this.currentValue;
      
      // 保留小数位数
      if (this.optionsSetup.decimal !== undefined) {
        value = parseFloat(value).toFixed(this.optionsSetup.decimal);
      }
      
      // 千分位分隔符
      if (this.optionsSetup.thousandth) {
        const parts = value.toString().split('.');
        parts[0] = parts[0].replace(/\B(?=(\d{3})+(?!\d))/g, ',');
        value = parts.join('.');
      }
      
      return value;
    },
    allComponentLinkage() {
      return this.$store.state.designer.allComponentLinkage;
    },
  },
  watch: {
    value: {
      handler(val) {
        this.options = val;
        this.optionsData = val.data;
        this.optionsSetup = val.setup;
        this.setOptionsData();
      },
      deep: true
    }
  },
  mounted() {
    this.options = this.value;
    this.optionsData = this.value.data;
    this.optionsSetup = this.value.setup;
    targetWidgetLinkageLogic(this);
    this.setOptionsData();
  },
  beforeDestroy() {
    if (this.flagInter) {
      clearInterval(this.flagInter);
    }
  },
  methods: {
    setOptionsData(e, paramsConfig) {
      const optionsData = this.optionsData;
      optionsData.dynamicData = optionsData.dynamicData || {};
      const myDynamicData = optionsData.dynamicData;
      clearInterval(this.flagInter);

      if (
        e &&
        optionsData.dataType !== "staticData" &&
        Object.keys(myDynamicData.contextData).length
      ) {
        const keyArr = Object.keys(myDynamicData.contextData);
        paramsConfig.forEach((conf) => {
          if (keyArr.includes(conf.targetKey)) {
            myDynamicData.contextData[conf.targetKey] = e[conf.originKey];
          }
        });
      }

      if (optionsData.dataType === "staticData") {
        this.staticDataFn(optionsData.staticData);
      } else {
        this.dynamicDataFn(optionsData.dynamicData, optionsData.refreshTime);
      }
    },
    staticDataFn(val) {
      const numValue = parseFloat(val) || 0;
      this.animateValue(numValue);
    },
    dynamicDataFn(val, refreshTime) {
      if (!val) return;
      if (this.ispreview) {
        this.getEchartData(val);
        this.flagInter = setInterval(() => {
          this.getEchartData(val);
        }, refreshTime);
      } else {
        this.getEchartData(val);
      }
    },
    getEchartData(val) {
      const data = this.queryEchartsData(val);
      data.then(res => {
        if (res && res.length > 0) {
          const numValue = parseFloat(res[0].value) || 0;
          this.animateValue(numValue);
        }
      });
    },
    animateValue(targetValue) {
      // 立即更新previousValue为当前值
      this.previousValue = this.currentValue;
      // 设置目标值
      this.targetValue = targetValue;
      
      // 如果不需要动画效果，直接更新值
      if (!this.optionsSetup.duration || this.optionsSetup.duration <= 0) {
        this.currentValue = targetValue;
        return;
      }
      
      this.animationDuration = this.optionsSetup.duration;
      this.animationStartTime = Date.now();
      this.animationRunning = true;
      
      this.runAnimation();
    },
    runAnimation() {
      if (!this.animationRunning) return;
      
      const now = Date.now();
      const elapsed = now - this.animationStartTime;
      const progress = Math.min(elapsed / this.animationDuration, 1);
      
      // 使用缓动函数使动画更自然
      const easeProgress = 1 - Math.pow(1 - progress, 3);
      
      // 计算当前帧的值
      this.currentValue = this.previousValue + (this.targetValue - this.previousValue) * easeProgress;
      
      if (progress < 1) {
        requestAnimationFrame(() => this.runAnimation());
      } else {
        this.animationRunning = false;
        // 确保最终值准确
        this.currentValue = this.targetValue;
      }
      
      this.$forceUpdate();
    }
  }
};
</script>

<style scoped lang="scss">
.flipper-container {
  width: 100%;
  height: 100%;
}

.flipper-wrapper {
  width: 100%;
  height: 100%;
  display: flex;
  align-items: center;
  justify-content: center;
}

.flipper-content {
  display: flex;
  align-items: center;
  justify-content: center;
  width: 100%;
  height: 100%;
}

.flipper-prefix,
.flipper-suffix {
  white-space: nowrap;
}

.flipper-value {
  font-weight: bold;
}

.flipper-digit {
  font-weight: bold;
  min-width: 1em;
  text-align: center;
  // 移除默认的padding，改用配置项控制
}
</style>